//
//  EncryptionMiddleware.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/4/19.
//

class EncryptionMiddleware: RequestMiddleware {
    func handleRequest<T: API>(_ api: T, body: Data) throws -> (Data, T) {
        // 判断是否需要加密（例如，根据 API 类型或者接口的要求）
        if api.requiresEncryption {
            // 对请求体进行加密
            let jsonString = String(data: body, encoding: .utf8)!
            Encrypt.shared.generateAESKey() // 生成AES会话密钥
            guard let encryptedString = Encrypt.shared.encrypt(jsonString) else { //通过AES密钥加密数据
                throw NetworkError.networkError(NSError(domain: "EncryptionError", code: -1, userInfo: nil))
            }
            var modifiedAPI = api
            var modifiedHeaders = api.headers
            let encryptKey = Encrypt.shared.rsaEncryptRaw()
            modifiedHeaders["encrypt-key"] = encryptKey
//            modifiedHeaders["Content-Type"] = "text/plain"
            modifiedAPI = modifiedAPI.updatedHeaders(modifiedHeaders)
            let encryptedData = encryptedString.data(using: .utf8)!
            return (encryptedData, modifiedAPI)
        } else {
            return (body, api)
        }
    }
    
    func handleResponse<T>(_ api: T, data: Data, error: (any Error)?) -> Data where T : API {
        return data
    }
}

